package com.dwxt.community.aiequipment.sellmachine.controller;

import com.dwxt.community.aiequipment.aibin.entity.enumeration.*;
import com.dwxt.community.aiequipment.enumeration.*;
import com.dwxt.community.aiequipment.sellmachine.entity.*;
import com.dwxt.community.aiequipment.sellmachine.entity.enumeration.*;
import com.dwxt.community.aiequipment.sellmachine.service.*;
import com.dwxt.community.aiequipment.util.*;
import org.apache.commons.io.*;
import org.apache.commons.lang3.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * @program: intelligentcity
 * @description: 售货机控制层
 * @author
 * @create: 2020/05/13
 */
@RestController
@RequestMapping("/cms/smj")
public class SellMachineProtocolControllerAdmin {

    private Logger logger = LoggerFactory.getLogger(SellMachineProtocolControllerAdmin.class);

    @Autowired
    private SellMachineService sellMachineService;
    @Autowired
    private SellMachineBreakdownRecordService sellMachineBreakdownRecordService;
    @Autowired
    private SellMachineOrderService sellMachineOrderService;


    /**
     * 握手
     *
     * @return
     */
    @RequestMapping("/ws")
    public void ws(HttpServletRequest request, HttpServletResponse response) {
        logger.info("售卖机握手请求========>");
        response.setContentType("text/html;charset=UTF-8");
        try {
            byte[] dataBytes = IOUtils.toByteArray(request.getInputStream());
            int[] dataInts = DataHandler.toIntArray(dataBytes);
            int i = ParseFenleiUtil.verifyFormat(dataInts);
            logger.info("售卖机【{}】握手请求数据 => {}",ParseFenleiUtil.parseDeviceId(dataInts,4,15), Arrays.toString(dataBytes));
            int[] responseInts;
            if (i == AiBinstatueEnum.OK.getCode()) {
                SellMachine sellMachine = ParseFenleiUtil.parseSmjWs(dataInts);
                sellMachineService.wsInsertOrUpdate(sellMachine);
                responseInts = ReplyBaseUtil.ok(WsConstant.VERIFY_REPLY_TOTAL_LENGTH);
            } else {
                responseInts = ReplyBaseUtil.bulidCrcBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, AiBinstatueEnum.OK.getCode(), i);
            }
            ServletOutputStream outputStream = response.getOutputStream();
            logger.info("售卖机握手回复数据 => {}", Arrays.toString(DataHandler.toByteArray(responseInts)));
            outputStream.write(DataHandler.toByteArray(responseInts));
            outputStream.flush();
        } catch (IOException e) {
            logger.error("售卖机握手接口错误=>{}", e.getMessage());
            e.printStackTrace();
        }

    }


    /**
     * 故障
     *
     * @return
     */
    @RequestMapping("/breakdown")
    public void breakdown(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        try {
            byte[] dataBytes = IOUtils.toByteArray(request.getInputStream());
            int[] dataInts = DataHandler.toIntArray(dataBytes);
            int res = ParseFenleiUtil.verifyFormat(dataInts);
            logger.info("售卖机【{}】breakdown请求数据 => {}", ParseFenleiUtil.parseDeviceId(dataInts,4,15),Arrays.toString(dataBytes));
            int[] responseInts;
            if (res == AiBinstatueEnum.OK.getCode()) {
                SellMachineBreakdownRecord breakdownRecord = ParseFenleiUtil.parseSmjBreakdown(dataInts);
                sellMachineBreakdownRecordService.insert(breakdownRecord);
                responseInts = ReplyBaseUtil.ok(WsConstant.VERIFY_REPLY_TOTAL_LENGTH);
            } else {
                responseInts = ReplyBaseUtil.bulidCrcBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, AiBinstatueEnum.OK.getCode(), res);
            }
            logger.info("售卖机breakdown回复数据 => {}", Arrays.toString(DataHandler.toByteArray(responseInts)));
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(DataHandler.toByteArray(responseInts));
            outputStream.flush();
        } catch (Exception e) {
            logger.error("售卖机breakdown接口错误=>{}", e.getMessage());
            e.printStackTrace();
        }

    }


    /**
     * 查询支付连接  支付信息  积分兑换等
     *
     * @return
     */
    @RequestMapping("/netpay")
    public void netpay(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        try {
            byte[] dataBytes = IOUtils.toByteArray(request.getInputStream());
            int[] dataInts = DataHandler.toIntArray(dataBytes);
            int res = ParseFenleiUtil.verifyFormat(dataInts);
            logger.info("售卖机【{}】netpay请求数据 => {}",ParseFenleiUtil.parseDeviceId(dataInts,4,15),Arrays.toString(dataBytes));
            if (res == AiBinstatueEnum.OK.getCode()) {
                SellMachineNetpay sellMachineNetpay = ParseFenleiUtil.parseNetPay(dataInts);
                if (ObjectUtils.isNotEmpty(sellMachineNetpay)) {
                    logger.info("售卖机netpay{} => {}",NetpayTypeEnum.getMsg(sellMachineNetpay.getNetPayType()),Arrays.toString(dataBytes));
                    dataInts = DataHandler.buildCrcArr(sellMachineService.netPay(request.getRemoteAddr(),sellMachineNetpay));
                    logger.info("售卖机netpay{}回复数据 => {}",NetpayTypeEnum.getMsg(sellMachineNetpay.getNetPayType()),Arrays.toString(DataHandler.toByteArray(dataInts)));
                } else {
                    dataInts = ReplyBaseUtil.bulidCrcBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.DATA_PARSE_ERROR.getCode());
                }
            } else {
                dataInts = ReplyBaseUtil.bulidCrcBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), res);
            }
            logger.info("售卖机netpay回复数据 => {}",Arrays.toString(DataHandler.toByteArray(dataInts)));
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(DataHandler.toByteArray(dataInts));
            outputStream.flush();
        } catch (Exception e) {
            logger.error("售卖机netpay接口错误=>{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 积分记录 兑换领取资格查询
     *
     * @return
     */
    @RequestMapping("/newReceive")
    public void newReceive(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        try {
            byte[] dataBytes = IOUtils.toByteArray(request.getInputStream());
            int[] dataInts = DataHandler.toIntArray(dataBytes);
            int res = ParseFenleiUtil.verifyFormat(dataInts);
            logger.info("售卖机【{}】newReceive请求数据 => {}", ParseFenleiUtil.parseDeviceId(dataInts,4,15),Arrays.toString(dataBytes));
            if (res == AiBinstatueEnum.OK.getCode()) {
                //解析数据
                SellMachineNetpay sellMachineNetpay = ParseFenleiUtil.newReceive(dataInts);
                if (ObjectUtils.isNotEmpty(sellMachineNetpay)) {
                    //业务逻辑
                    dataInts = DataHandler.buildCrcArr(sellMachineService.newReceive(sellMachineNetpay));
                } else {
                    dataInts = ReplyBaseUtil.bulidCrcBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), ResStatueEnum.DATA_PARSE_ERROR.getCode());
                }
            } else {
                dataInts = ReplyBaseUtil.bulidCrcBaseResponseInts(WsConstant.VERIFY_REPLY_TOTAL_LENGTH, ResStatueEnum.OK.getCode(), res);
            }
            logger.info("售卖机newReceive回复数据 => {}", Arrays.toString(DataHandler.toByteArray(dataInts)));
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(DataHandler.toByteArray(dataInts));
            outputStream.flush();
        } catch (Exception e) {
            logger.error("售卖机newReceive接口错误=>{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 微信支付回调接口
     */
    @RequestMapping("/wxCallback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("售卖机微信支付回调");
        String resXml = "";
        try {
            resXml = getResXmlString(request);
            logger.info("微信支付异步通知请求包: {}", resXml);
            //修改订单状态
            String payBack = sellMachineOrderService.checkParamsWX(resXml);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(payBack);
        } catch (Exception e) {
            logger.error("微信支付回调通知失败", e);
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(result);
        }
    }
    private String getResXmlString(HttpServletRequest request) throws IOException {
        InputStream is = request.getInputStream();
        //将InputStream转换成String
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        return sb.toString();
    }


    /**
     * 支付宝支付回调
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/zfbCallback")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("售卖机支付宝支付回调");
        PrintWriter responseWriter = response.getWriter();
        try {
            Map<String, String> params = getZFBRespMap(request);
            String result = sellMachineOrderService.checkParamsZFB(params);
            responseWriter.write(result);
        } catch (Exception e) {
            logger.error(e.toString());
            responseWriter.write("fail");
        }
    }

    private Map<String, String> getZFBRespMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            logger.info(name + "：" + valueStr);
            params.put(name, valueStr);
        }
        return params;
    }

}
